package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class UserJob {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 每日工单量列表初始化
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception{
        //todo:查询用户列表
        if (param == null) {
            throw new LogicException("工单量初始化缺少传参");
        }
        //0代表初始化当天数据,加1代表明天
        int plusDays = 0;
        if ("1".equals(param)) {
            plusDays = 1;
        }
        //查询用户
        List<UserEntity> userList = userService.list();
        for (UserEntity userEntity : userList) {
            //排除管理员
            if (userEntity.getRoleId() != 1){
                String date = LocalDateTime.now().plusDays(plusDays).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
                //构建key
                String key = VMSystem.REGION_TASK_KEY_PREF
                        + date +"."
                        + userEntity.getRegionId() + "."
                        + userEntity.getRoleCode();
                //存入redis
                redisTemplate.opsForZSet().add(key,userEntity.getId(),0);
                redisTemplate.expire(key, Duration.ofDays(2));
            }
        }

        return ReturnT.SUCCESS;
    }
}
